import L from '@/components/Leaflet/leaflet'

class AreaMeasure {

    constructor(map) {
        this.mapInstance = map

        this._enabled = false

        this.points = []
        //markers:[], 
        this.color = "red"
        this.layers = L.layerGroup()
        this.polygon = null
        this.marker = null

        this.deleteIcon =  L.divIcon({className: 'el-icon-close leaflet-custom-areameasure-close'});
    }


    init() {
        this.points = [];
        this.polygon = null;
        this.marker = null;
        this.mapInstance.on("click", (e) => this.clickEvent(e))
        this.mapInstance.on("dblclick", (e) => this.dblclickEvent(e))
        L.DomUtil.addClass(this.mapInstance._container, 'leaflet-custom-areameasure-cursor');
        this._enabled = true
    }


    close(latlng) {
        this.marker = L.marker(latlng, {
            icon: this.deleteIcon
        })
        .addTo(this.mapInstance)
        .on("click", function (e) {
            if (this.polygon) this.mapInstance.removeLayer(this.polygon);
            if (this.marker) this.marker.remove();
        });
    }


    clickEvent (e) { 
        this.mapInstance.doubleClickZoom.disable(); 
        // 添加点信息 
        this.points.push(e.latlng); 
        // 添加面 
        this.mapInstance.on("mousemove", (e) => this.mousemove(e)); 
    }


    mousemove (e) { 
        this.points.push(e.latlng); 
        if (this.polygon) this.mapInstance.removeLayer(this.polygon); 
        this.polygon = L.polygon(this.points, { 
            showMeasurements: true, 
            color: "red", 
        }); 
        this.polygon.addTo(this.layers); 
        this.layers.addTo(this.mapInstance); 
        this.points.pop(); 
    }

    dblclickEvent (e) { 
        // 双击结束 
        this.polygon.addTo(this.layers); 
        this.close(e.latlng); 

        this.mapInstance.off("click") 
        this.mapInstance.off("mousemove") 
        this.mapInstance.off("dblclick")
        L.DomUtil.removeClass(this.mapInstance._container,'leaflet-custom-areameasure-cursor'); 
    }


    destory () { 
        if (this.polygon) this.mapInstance.removeLayer(this.polygon); 
        if (this.marker) this.marker.remove(); 
        L.DomUtil.removeClass(this.mapInstance._container,'leaflet-custom-areameasure-cursor'); 
        this._enabled = false
    }
}


export default AreaMeasure